package com.kdtech.analyse.Bbs;
import com.kdtech.crawler.at.UrlArgumentTop;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.DoMainUtils;
import com.kdtech.utils.HtmlCleaner;
import com.kdtech.utils.NumberUtils;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import com.kdtech.crawler.CrawlHTML;

import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.analyse.AnalyseNews;
import com.kdtech.utils.RegexUtils;

public class OffensivismBbsAnalyse implements AnalyseNews {

	
	public boolean isDetailPage(String url) {
		String[] regex = {
				"http://www.offensivism.com/phpBB2/viewtopic.php\\?f=[0-9]*&t=[0-9]*",
				"http://www.offensivism.com/phpBB2/viewtopic.php\\?f=[0-9]*&sid=[a-z0-9&]*&start=0&t=[0-9]*",
				"http://www.offensivism.com/phpBB2/viewtopic.php\\?f=[0-9]*&p=[0-9]*&sid=[a-z0-9&]*&t=[0-9]*",
				"http://www.offensivism.com/phpBB2/viewtopic.php\\?f=[0-9]*&sid=[a-z0-9&]*&t=[0-9]*"
		};
		return RegexUtils.matchAny(url, regex);
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {
		if (!isDetailPage(urlMeta.getUrl())) {
		}
		NewsMeta bbs = new NewsMeta();
		if (urlMeta.getHtml() == null) {
		}
		String htmltxt = urlMeta.getHtml();
		String url = urlMeta.getUrl();

		bbs.setUrl(url);
		String title = null;
		String content = null;
		Long date = null;
		String author = null;

		Document doc = Jsoup.parse(htmltxt);

		doc.select("td.gensmall > div > b").remove();
		Elements titleList = doc.select("td.gensmall > div");
		if(titleList.size()>1)
		{
			title = titleList.get(0).text();
		}
		date = DateUtils.matchDate(doc.select("td.gensmall").text());
		content = HtmlCleaner.getContentHtml(url, doc.select("div.postbody"));
		Elements authorList = doc.select("b.postauthor");
		if(authorList.size()>1)
		{
			author = authorList.get(0).text();
		}
		bbs.setTitle(title);
		bbs.setContent(content);
		bbs.setDate(date);
		bbs.setAuthor(author);
		/**
		 * 解析用于更新的地址
		 */
		bbs.setUpdateUrl(url);
		return bbs;
	}

	
	public NewsMeta Update(NewsMeta meta) {
		return null;
	}

	public static void main(String[] args) {
		OffensivismBbsAnalyse a = new OffensivismBbsAnalyse();

		String url = "http://www.offensivism.com/phpBB2/viewtopic.php?f=10&sid=05b033af16e869df016cc5c898e91b0e&t=849";
		System.out.println(UrlArgumentTop.FromatUrl(url));
		System.out.println(DoMainUtils.GetDomainName(url));
		if (!a.isDetailPage(url)) {
			System.out.println("不匹配规则");
		} else {
			UrlMeta meta = CrawlHTML.responseToURL(url);
			NewsMeta parserHtml = a.parserHtml(meta);
			System.out.println(parserHtml);
//			System.out.println(a.Update(parserHtml));
		}

	}
	

}
